<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert title="添加商品" type="info" center show-icon></el-alert>
      <el-steps :active="activeIndex - 0" finish-status="success" :space="200">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="newGood" :rules="newGoodRules" ref="newGoodFormRef">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" label-width="10%" prop="goods_name">
              <el-input v-model="newGood.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" label-width="10%" prop="goods_price">
              <el-input v-model="newGood.goods_price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" label-width="10%" prop="goods_number" type="number">
              <el-input v-model="newGood.goods_number" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" label-width="10%" prop="goods_weight" type="number">
              <el-input v-model="newGood.goods_weight" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" label-width="10%">
              <!-- options指定数据源，props指定配置对象label、children是哪个 -->
              <el-cascader
                v-model="cascaderVal"
                :options="parentCateList"
                expandTrigger="hover"
                :props="props"
                @change="handleCascaderChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-tag
              v-for="(item, index) in newGood.attrs"
              :key="item.id"
              @close="removeAttr(index)"
              closable
            >{{item}}</el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm()"
              @blur="handleInputConfirm()"
              style="width:100px"
            ></el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput()">+ New Tag</el-button>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">商品属性</el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <!-- action表示图片上传的api地址 -->
            <el-upload
              action="http://127.0.0.1:4396/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handlePicSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="newGood.goods_introduce"></quill-editor>
          </el-tab-pane>
          <el-tab-pane name="5" label="完成">
            <el-button @click="admitGood">确认添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="picPreview" width="30%">
      <img :src="previewPath" width="100%" alt="商品图片" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: '0',
      newGood: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: 1,
        goods_introduce: '',
        goods_cat: [],
        id: '',
        attrs: [],
        pics: []
      },
      cascaderVal: [],
      inputVisible: false,
      inputValue: '',
      newGoodRules: {
        goods_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        goods_price: [{ required: true, message: '不能为空', trigger: 'blur' }],
        goods_number: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        goods_weight: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      // 设置级联选择器属性
      props: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 级联选择器显示数据
      parentCateList: [],
      // 级联选择器选择数据
      cascaderVal: [],
      // 图片上传的请求头
      headerObj: {
        Authorization: window.localStorage.getItem('token')
      },
      // 图片
      previewPath: '',
      picPreview: false
    }
  },
  created() {
    this.getParentCateList()
  },
  methods: {
    async getParentCateList() {
      // 传递参数需要params
      this.$http.get('categories').then(res => {
        if (res.data.meta.status != 200) {
          return this.$message.error('获取数据失败')
        }
        this.parentCateList = res.data.data
        console.log(this.parentCateList)
      })
    },
    async handleInputConfirm(data) {
      console.log(data)
      // 对输入的数据进行检验
      if (data.inputValue.trim().length === 0) {
        data.inputVisible = false
        data.inputValue = ''
        return this.$message.error('输入不能为空')
      }
      // 检验成功后提交
      data.attr_vals.push(data.inputValue.trim())
      data.inputVisible = false
      data.inputValue = ''
      const res = await this.saveAttrValves(data)
      console.log(res)
      if (res.data.meta.status != 200) {
        return this.$message.error('添加失败')
      }
      return this.$message.success('添加成功！')
    },
    handleInputConfirm() {
      // 对输入的数据进行检验
      if (this.inputValue.trim().length === 0) {
        this.inputVisible = false
        this.inputValue = ''
        return this.$message.error('输入不能为空')
      }
      this.newGood.attrs.push(this.inputValue)
      this.inputValue = ''
      this.inputVisible = false
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 级联选择器变化
    handleCascaderChange() {
      console.log(this.cascaderVal)
    },
    // 图片移除
    handleRemove(file) {
      const i = this.newGood.pics.findIndex(item => item.pics === file.url)
      this.newGood.pics.splice(i, 1)
      console.log(this.newGood)
    },
    // 图片上传预览
    handlePreview(file) {
      this.previewPath = file.url
      this.picPreview = true
    },
    // 图片上传成功
    handlePicSuccess(res) {
      // console.log(res)
      const picInfo = { pic: res.data.tmp_path }
      this.newGood.pics.push(picInfo)
      console.log(this.newGood)
    },
    // 确认添加
    async admitGood() {
      if (this.cascaderVal.length === 0) {
        this.activeIndex = '0'
        this.$message.closeAll()
        return this.$message.error('请选择分类')
      }
      this.newGood.goods_cat = this.cascaderVal.join()
      console.log(this.newGood)
      const { data: res } = await this.$http.post(`goods`, this.newGood)
      console.log(res)
      if (res.meta.status != 201) {
        return this.$message.error('操作失败')
      }
      this.$message.success('操作成功')
    },
    // 离开pane判断
    beforeLeave() {
      console.log(this.activeIndex)
      var calid = true
      if (this.activeIndex === '0') {
        this.$refs.newGoodFormRef.validate(valid => {
          calid = valid
          if (!valid) {
            this.activeIndex = '0'
            this.$message.closeAll()
            this.$message.error('请检查输入')
          }
        })
      }
      return calid
    }
  },
  computed: {
    cateId() {
      if (this.newGood.goods_cat.length === 3) {
        return this.newGood.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
  .el-steps {
    margin-left: 15%;
    margin-top: 20px;
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .el-tag {
    margin-right: 15px;
  }
}
</style>